﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using CoreShop.App;
using CoreShop.Library;
using CoreShop.Services;
using System.Windows.Forms;
using CoreShop.Model;
using CoreShop.PrintService;
using SqlSugar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using Yitter.IdGenerator;
using SqlSugar.Extensions;
using FastMember;
using Sunny.UI;
using Sunny.UI.Win32;
using CoreShop.Model.FromBody;
using CoreShop.App.Units.Interface;
using CoreShop.Library.Units;
using static CoreShop.Services.PosRemoteServices;
using System.Threading.Tasks;

namespace CoreShop
{
    public class MemberUtil
    {       
        /// <summary>
        /// 会员保存
        /// </summary>
        /// <param name="member"></param>
        public void SaveUserInfo(corecmsuser member)
        {
            if (member == null) return;
            corecmsuserServices userSrv = new corecmsuserServices();
            var memberModel = userSrv.GetById(member.id);
            if (memberModel == null)
            {
                member.parentId = AppConstVars.sysUser.id;
                member.sysUserId = AppConstVars.sysUser.id;
                member.storeId = AppConstVars.sysUser.storeId;
                member.corpId = AppConstVars.sysUser.corpId;
                member.creatorId = AppConstVars.sysUser.id;
                member.createTime = DateTime.Now;
                member.passWord = "000000";
                member.avatarImage = "";
                member.quantity = 0;
                member.isDelete = false;
                member.source = 0;
                member.shareFlag = false;
                member.modifyTime = 0;
                userSrv.Insert(member);
            }
            else
            {
                memberModel.balance = member.balance;
                memberModel.giftBalance = member.giftBalance;
                memberModel.userName = member.userName;
                memberModel.sex = member.sex;
                memberModel.mobile = member.mobile;
                memberModel.status = member.status;
                userSrv.Update(memberModel);
            }
        }

        /// <summary>
        /// 会员充值
        /// </summary>
        /// <param name="member"></param>
        public void SetUserDeposit(corecmsuser member)
        {
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择会员。");
                return;
            }            
            try
            {
                frmUserDeposit frm = new frmUserDeposit(member);
                frm.ShowDialog();
                frm.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 会员积分
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void SetUserPoint(corecmsuser member)
        {
            try
            {
                if ((member == null) || (member.id == 0))
                {
                    UIMessageBox.Show("没有选择会员。");
                    return;
                }
                frmPoint frm = new frmPoint(member);
                frm.ShowDialog();
                frm.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 执行会员价,1.0方法：GetSaleVipLevelRightPrice
        /// </summary>
        /// <param name="custoType"></param>
        /// <returns></returns>
        public void SetMemberPrice(corecmsfoodordering orderInfo, corecmsuser member, corecmsfoodspec foodspec)
        {
            if ((orderInfo.dataType == (int)GlobalEnumVars.OrderingDataType.Present)
                || (orderInfo.dataType == (int)GlobalEnumVars.OrderingDataType.Refund)
                || (orderInfo.itemType == (int)GlobalEnumVars.FoodType.PackChild)) return;

            if (!orderInfo.disItem) return;//不允许打折

            decimal VipPrice = orderInfo.price;

            if (member.VipLevelRightInfo != null)
            {
                //消费价格类型  0标准售价 1售价2 2售价3 3售价4
                int salePriceType = CommFunc.ConvertToInt32(member.VipLevelRightInfo.salePriceType);
                //消费折扣率
                decimal salePriceDis = member.VipLevelRightInfo.salePriceDis.ObjToDecimal();
                //折扣和优惠券是否互斥 0 是 1否
                int shareCouponExclusion = CommFunc.ConvertToInt32(member.VipLevelRightInfo.shareCouponExclusion);
                //生日折扣  0标准售价 1售价2 2售价3 3售价4
                int birthdayPriceType = CommFunc.ConvertToInt32(member.VipLevelRightInfo.birthdayPriceType);
                //生日折扣率
                decimal birthdayPriceDis = CommFunc.ConvertToDecimal(member.VipLevelRightInfo.birthdayPriceDis);

                if (!string.IsNullOrEmpty(member.birthday.ToString()) && DateTime.Now.Date == Convert.ToDateTime(member.birthday).Date)
                {
                    //正常线下折扣
                    decimal VipPriceNew = GetVipPriceLevelRight(foodspec, salePriceType, salePriceDis, orderInfo.price);

                    //会员生日折扣
                    decimal BirthdayVipPrice = GetVipPriceLevelRight(foodspec, birthdayPriceType, birthdayPriceDis, orderInfo.price);

                    VipPrice = BirthdayVipPrice > VipPriceNew ? VipPriceNew : BirthdayVipPrice;
                }
                else
                {
                    //正常线下折扣
                    VipPrice = GetVipPriceLevelRight(foodspec, salePriceType, salePriceDis, orderInfo.price);
                }
            }
            if (VipPrice < orderInfo.realPrice) orderInfo.realPrice = VipPrice;
            if (orderInfo.price != 0) orderInfo.discount = orderInfo.realPrice / orderInfo.price;
            orderInfo.realAmount = orderInfo.realPrice * orderInfo.quantity;
            orderInfo.allAmount = orderInfo.realAmount + orderInfo.feedAmount + orderInfo.taskAmount;            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="gsProductModel">商品对象</param>
        /// <param name="PriceType"> 0标准售价 1售价2 2售价3 3售价4 </param>
        /// <param name="PriceDis">折扣率 0-1之间</param>
        /// <returns></returns>
        public static decimal GetVipPriceLevelRight(corecmsfoodspec foodspec, int PriceType, decimal PriceDis, decimal sourcePrice)
        {
            if (foodspec.spuTypeId == (int)GlobalEnumVars.GoodsSpuType.VirtualGoods) 
                return sourcePrice * PriceDis;

            if (foodspec.posPrice == 0) return sourcePrice * PriceDis;

            // 初始化最终价格为0
            decimal finalPrice = 0;

            // 先获取根据 PriceType 得到的对应价格
            switch (PriceType)
            {
                case 0: // 标准售价
                    finalPrice = foodspec.posPrice;
                    break;
                case 1: // 售价2
                    finalPrice = foodspec.vipPrice;
                    break;
                case 2: // 售价3
                    finalPrice = foodspec.vvipPrice;
                    break;
                case 3: // 售价4
                    finalPrice = foodspec.commPrice;
                    break;
            }

            // 如果对应的价格为0，则从上一个价格查找
            if (finalPrice == 0)
            {
                switch (PriceType)
                {
                    case 1: // 如果售价2为0，取售价1（saPrice）
                        finalPrice = foodspec.posPrice;
                        break;
                    case 2: // 如果售价3为0，取售价2
                        finalPrice = foodspec.vipPrice;
                        if (finalPrice == 0) // 如果售价2也为0，则取售价1
                        {
                            finalPrice = foodspec.posPrice;
                        }
                        break;
                    case 3: // 如果售价4为0，取售价3
                        finalPrice = foodspec.vvipPrice;
                        if (finalPrice == 0) // 如果售价3也为0，则取售价2
                        {
                            finalPrice = foodspec.vipPrice;
                            if (finalPrice == 0) // 如果售价2也为0，则取售价1
                            {
                                finalPrice = foodspec.posPrice;
                            }
                        }
                        break;
                }
            }

            // 最终价格计算
            return finalPrice * PriceDis;
        }


        /// <summary>
        /// 会员订单数据变化
        /// </summary>
        /// <param name="custoType"></param>
        /// <returns></returns>
        public bool SetMemberData(long orderId, corecmsuser member)
        {
            bool result = false;
            long mMemberId = 0;
            if (orderId > 0)
            {
                if (member != null)
                    mMemberId = member.id;
                result = new corecmsfoodorderingmasterServices().Update(a => new corecmsfoodorderingmaster()
                {
                    userId = mMemberId,
                }, a => a.orderId == orderId);
            }

            var orderlList = new corecmsfoodorderingServices().QueryByOrderId(orderId);
            if ((orderlList == null) || (orderlList.Count == 0)) return false;

            var foodIds = orderlList.Select(p => p.foodSpecId).ToList();
            var foodspecs = new corecmsfoodspecServices().GetList().Where(p => foodIds.Contains(p.id)).ToList();
            foreach (var orderInfo in orderlList)
            {
                if ((orderInfo.dataType == (int)GlobalEnumVars.OrderingDataType.Present)
                    || (orderInfo.dataType == (int)GlobalEnumVars.OrderingDataType.Refund) || (orderInfo.itemType == (int)GlobalEnumVars.FoodType.GroupChild)) continue;
                if (member == null)
                {
                    orderInfo.realPrice = orderInfo.price;
                    orderInfo.discount = 1;
                    orderInfo.realAmount = orderInfo.realPrice * orderInfo.quantity;
                    orderInfo.allAmount = orderInfo.realAmount + orderInfo.feedAmount + orderInfo.taskAmount;
                }
                else
                {
                    mMemberId = member.id;
                    var foodspec = foodspecs.Find(p => p.id == orderInfo.foodSpecId);
                    SetMemberPrice(orderInfo, member, foodspec);
                }
            }
            string msg = "";
            new ActivitieUtil().SetOrderingPromotionAll(orderlList, member, ref msg);//计算促销
            result = new corecmsfoodorderingServices().Change<corecmsfoodordering>().UpdateRange(orderlList);
            return result;
        }
                
        /// <summary>
        /// 加载会员优惠券列表
        /// </summary>
        public async static Task<AsyncReturnModel> SetCouponList(List<corecmsfoodordering> orderingDetail,List<VipCouponInfoModel> vipCouponInfos, sysuser sysuser,decimal debtAmount)
        {
            AsyncReturnModel asyncReturn = new AsyncReturnModel();
            VipCouponInfoModel infoModel = vipCouponInfos.FirstOrDefault();            
            ReturnModel returnModel = await MemberApiUtil.SetCouponInfo(infoModel.couponNo, sysuser);

            if (returnModel.Status != ReturnStatus.Success)
            {
                asyncReturn.msg = $"核销券失败,{returnModel.MessageOrString}";
                return asyncReturn;
            }

            CouponInfoDataModel couponInfoData = returnModel.MessageOrString.JsonToEntity<CouponInfoDataModel>();

            if (couponInfoData.code != 200)
            {
                asyncReturn.msg = $"获取券信息出现错误,请稍后再试:{couponInfoData.msg}";
                return asyncReturn;
            }

            if (couponInfoData.data.couponTypeId != GlobalEnumVars.CouponEnum.代金券.GetHashCode().ToString()
            && couponInfoData.data.couponTypeId != GlobalEnumVars.CouponEnum.满减券.GetHashCode().ToString()
            && couponInfoData.data.couponTypeId != GlobalEnumVars.CouponEnum.折扣券.GetHashCode().ToString())
            {
                asyncReturn.msg = "券不可核销";
                return asyncReturn;
            }

            if (couponInfoData.data.couponTypeId == GlobalEnumVars.CouponEnum.满减券.GetHashCode().ToString())
            {
                if (debtAmount < Convert.ToDecimal(couponInfoData.data.verifyAmount))
                {
                    asyncReturn.msg = "核销失败，不满足最低门栏";
                    return asyncReturn;
                }
            }

            returnModel = await MemberApiUtil.UseCouponInfo(orderingDetail, couponInfoData, debtAmount,AppConstVars.sysStore, sysuser);

            if (returnModel.Status != ReturnStatus.Success)
            {
                asyncReturn.msg = $"核销失败:{returnModel.MessageOrString}";
                return asyncReturn;
            }

            ApiReturnModel apiReturnModel = returnModel.MessageOrString.JsonToEntity<ApiReturnModel>();

            if (apiReturnModel.code != 200)
            {
                asyncReturn.msg = $"核销失败:{apiReturnModel.msg}";
                return asyncReturn;
            }
            asyncReturn.status = true;
            return asyncReturn;
        }

    }
}
